package cn.yh.register.msm.service.impl;

import cn.yh.register.msm.service.MsmService;
import cn.yh.register.msm.util.ConstantPropertiesUtils;
import cn.yh.register.vo.msm.MsmVo;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class MsmServiceImpl implements MsmService {
    /**
     * 发送验证码
     * @param phone 手机号
     * @param code  验证码
     * @return 是否成功
     */
    @Override
    public boolean send(String phone, String code) {
        Map<String,Object> paramMap=new HashMap<>();
        paramMap.put("code",code);
       return this.send(phone,paramMap);
    }

    /**
     * 发送短信通知
     * @param msmVo 短信实体
     * @return 是否成功
     */
    @Override
    public Boolean send(MsmVo msmVo) {
        String phone = msmVo.getPhone();
        Map<String, Object> param = msmVo.getParam();

        return  this.send(phone,param);
    }

    /**
     * 发送短信
     * @param phone 手机号
     * @param paramMap 短信内容
     * @return 是否成功
     */
    private Boolean send(String phone, Map<String, Object> paramMap){
        if (StringUtils.isEmpty(phone)) {
            return false;
        }
        DefaultProfile profile = DefaultProfile.getProfile(
                ConstantPropertiesUtils.REGION_Id,
                ConstantPropertiesUtils.ACCESS_KEY_ID,
                ConstantPropertiesUtils.SECRECT);
        //发送短信的客户端
        IAcsClient client = new DefaultAcsClient(profile);
        //请求对象
        SendSmsRequest request = new SendSmsRequest();
        //签名名称
        request.setSignName("阿里云短信测试");
        //模板code
        request.setTemplateCode("SMS_154950909");
        //手机号
        request.setPhoneNumbers(phone);
        //短信内容
        request.setTemplateParam(JSONObject.toJSONString(paramMap));//设置验证码

        try {
            //发送短信
            SendSmsResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
            //返回的状态码 TODO  认证状态码
//            if ("OK".equals(response.getCode())) {
//            }
            System.out.println("已向手机号  "+phone+"  发送验短信  ："+paramMap+"  请注意查收");

            return true;
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        return false;
    }
}
